package org.sith.taskrunner.engine;

import org.sith.taskrunner.api.TaskRegisterResult;
import org.sith.taskrunner.api.TaskRunRequest;

import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.ejb.MessageDrivenContext;
import javax.ejb.TimerService;
import javax.jms.*;
import java.lang.IllegalStateException;
import java.util.logging.Logger;


@MessageDriven(name = "MyMessageBean", mappedName = "queue/TaskRunRequestQueue", activationConfig = {
        /* @ActivationConfigProperty(propertyName = "messageSelector",
      propertyValue = "NewsType = 'Sports' OR NewsType = 'Opinion'")
, @ActivationConfigProperty(propertyName = "subscriptionDurability",
      propertyValue = "Durable")
, @ActivationConfigProperty(propertyName = "clientId",
      propertyValue = "MyID")
, @ActivationConfigProperty(propertyName = "subscriptionName",
      propertyValue = "MySub"),*/
        @ActivationConfigProperty(propertyName = "destination", propertyValue = "queue/TaskRunRequestQueue")
})
public class MessageBean implements MessageListener {
    static final Logger logger = Logger.getLogger("MessageBean");
    @Resource
    public MessageDrivenContext mdc;

    @Resource(name = "JmsXA", mappedName = "java:JmsXA")
    private ConnectionFactory connectionFactory;
    @Resource(name = "queue/TaskRunRequestQueue", mappedName = "queue/TaskRegisterResultQueue")
    private Queue queue;


    public void onMessage(Message inMessage) {

        Connection connection = null;
        try {

            connection = connectionFactory.createConnection();
            Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            MessageProducer producer = session.createProducer(queue);
            Message message = session.createMessage();
            TaskRegisterResult taskRegisterResult = new TaskRegisterResult();

            Object objectProperty = inMessage.getObjectProperty(TaskRunRequest.TASK_RUNNER_REQUEST);
            if (objectProperty instanceof TaskRunRequest) {
                TaskRunRequest request = (TaskRunRequest) objectProperty;
                TaskRunnerQueue.getInstance().registerTask(request);
                taskRegisterResult.setResultType(TaskRegisterResult.ResultType.ACCEPTED);
            } else {
                taskRegisterResult.setResultType(TaskRegisterResult.ResultType.REJECTED);
                taskRegisterResult.setError(true);
                taskRegisterResult.setDescription("Object from message doesn't a TaskRunnerRequest instance");
            }

            message.setObjectProperty(TaskRegisterResult.RESULT_MESSAGE, taskRegisterResult);
            producer.send(message);



        } catch (JMSException e) {
            logger.severe(
                    "MessageBean.onMessage: JMSException: " + e.toString());
            e.printStackTrace();
            mdc.setRollbackOnly();
        } catch (Throwable te) {
            logger.severe("MessageBean.onMessage: Exception: " + te.toString());
            te.printStackTrace();
        } finally {
            if (connection != null) {
                try {
                    connection.close();
                } catch (JMSException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}
